import { onMounted, onUnmounted, ref } from 'vue'
import { WEBSOCKET } from "@/utils/constant.js"
import { global } from "@/utils/index"


export const getWebSocketUrl = () => {
	const userInfo = global.syncGetUerInfoByLocal()
	console.log('userInfo', userInfo, userInfo.memberId)
	return `${WEBSOCKET}${userInfo.memberId}`
}

const receivedMessages = ref([]) // 接受到的信息
export function useWebSocket() {
	// const registerMessageListeners = () => {
	//   if (!socketId) {
	//     console.warn('WebSocket not connected yet.');
	//     return;
	//   }
	//   uni.onSocketMessage((res) => {
	//     console.log('Received message:', res.data);
	//     messageListeners.forEach(listener => listener(res));
	//   });
	// };

	let socketId : string | null = null;
	const connectSocket = () => {
		console.log("开始连接")
		uni.connectSocket({
			url: getWebSocketUrl(),
			success: (res) => {
				socketId = res.socketTaskId;
				console.log('WebSocket connected successfully.', res);
			},
			fail: (err) => {
				console.error('WebSocket connection failed.', err);
			}
		});
	};

	const onSocketMessage = (callback : (res : any) => void) => {
		if (!socketId) {
			console.warn('WebSocket not connected yet. 没链接');
			return;
		}
		uni.onSocketMessage((res) => {
			callback(res);
		});
	};

	// 这里是socket信息
	uni.onSocketMessage((res) => {
		console.log('这里是监听socket信息', res)
		receivedMessages.value.push(res)
	});


	const sendSocketMessage = (data : any) => {
		if (!socketId) {
			console.warn('WebSocket not connected yet.');
			return;
		}
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success: () => {
				console.log('Message sent successfully.');
			},
			fail: (err) => {
				console.error('Failed to send message.', err);
			}
		});
	};

	const closeSocket = () => {
		if (socketId) {
			uni.closeSocket();
			socketId = null;
		}
	};


	// 连接 WebSocket 并在组件卸载时关闭连接
	const setupWebSocket = () => {
		onMounted(() => {
			console.log('可以链接')
			connectSocket()
		});

		onUnmounted(() => {
			console.log("关闭socket 链接")
			closeSocket()
		});
	};

	return {
		setupWebSocket,
		sendSocketMessage,
		receivedMessages,
		onSocketMessage,
		closeSocket
	};
}


